import { create } from 'zustand';
import { devtools } from 'zustand/middleware';
import db from '../database/db';

export interface PublishTask {
  id: string;
  title: string;
  content: string;
  images: string[];
  account: string;
  scheduledTime: string;
  status: 'pending' | 'running' | 'completed' | 'failed' | 'paused';
  progress: number;
  retryCount: number;
  maxRetries: number;
  createTime: string;
  updateTime: string;
}

interface PublishState {
  tasks: PublishTask[];
  loading: boolean;
  error: string | null;
  
  // Actions
  fetchTasks: () => Promise<void>;
  addTask: (task: Omit<PublishTask, 'id' | 'createTime' | 'updateTime'>) => Promise<void>;
  updateTask: (id: string, updates: Partial<PublishTask>) => Promise<void>;
  deleteTask: (id: string) => Promise<void>;
  getTasksByStatus: (status: PublishTask['status']) => PublishTask[];
  startTask: (id: string) => Promise<void>;
  pauseTask: (id: string) => Promise<void>;
}

export const usePublishStore = create<PublishState>()(
  devtools(
    (set, get) => ({
      tasks: [],
      loading: false,
      error: null,

      fetchTasks: async () => {
        set({ loading: true, error: null });
        try {
          const stmt = db.prepare('SELECT * FROM publish_tasks ORDER BY createTime DESC');
          const tasks = stmt.all() as any[];
          // 解析images字符串为数组
          const tasksWithImages = tasks.map(task => ({
            ...task,
                          images: task.images ? JSON.parse(task.images) as string[] : []
            })) as PublishTask[];
          set({ tasks: tasksWithImages, loading: false });
        } catch (error) {
          set({ error: (error as Error).message, loading: false });
        }
      },

      addTask: async (task) => {
        set({ loading: true, error: null });
        try {
          const id = Date.now().toString();
          const now = new Date().toISOString();
          const newTask: PublishTask = {
            ...task,
            id,
            createTime: now,
            updateTime: now,
          };

          const stmt = db.prepare(`
            INSERT INTO publish_tasks (id, title, content, images, account, scheduledTime, status, progress, retryCount, maxRetries, createTime, updateTime)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
          `);
          stmt.run(
            newTask.id,
            newTask.title,
            newTask.content,
            JSON.stringify(newTask.images),
            newTask.account,
            newTask.scheduledTime,
            newTask.status,
            newTask.progress,
            newTask.retryCount,
            newTask.maxRetries,
            newTask.createTime,
            newTask.updateTime
          );

          set(state => ({
            tasks: [newTask, ...state.tasks],
            loading: false
          }));
        } catch (error) {
          set({ error: (error as Error).message, loading: false });
        }
      },

      updateTask: async (id, updates) => {
        set({ loading: true, error: null });
        try {
          const now = new Date().toISOString();
          const updateFields = Object.keys(updates)
            .filter(key => key !== 'id')
            .map(key => `${key} = ?`)
            .join(', ');

          const stmt = db.prepare(`
            UPDATE publish_tasks 
            SET ${updateFields}, updateTime = ?
            WHERE id = ?
          `);

          const values = [...Object.values(updates), now, id];
          stmt.run(...values);

          set(state => ({
            tasks: state.tasks.map(task =>
              task.id === id ? { ...task, ...updates, updateTime: now } : task
            ),
            loading: false
          }));
        } catch (error) {
          set({ error: (error as Error).message, loading: false });
        }
      },

      deleteTask: async (id) => {
        set({ loading: true, error: null });
        try {
          const stmt = db.prepare('DELETE FROM publish_tasks WHERE id = ?');
          stmt.run(id);

          set(state => ({
            tasks: state.tasks.filter(task => task.id !== id),
            loading: false
          }));
        } catch (error) {
          set({ error: (error as Error).message, loading: false });
        }
      },

      getTasksByStatus: (status) => {
        return get().tasks.filter(task => task.status === status);
      },

      startTask: async (id) => {
        set({ loading: true, error: null });
        try {
          await get().updateTask(id, { status: 'running', progress: 0 });
          set({ loading: false });
        } catch (error) {
          set({ error: (error as Error).message, loading: false });
        }
      },

      pauseTask: async (id) => {
        set({ loading: true, error: null });
        try {
          await get().updateTask(id, { status: 'paused' });
          set({ loading: false });
        } catch (error) {
          set({ error: (error as Error).message, loading: false });
        }
      },
    }),
    {
      name: 'publish-store',
    }
  )
); 